﻿import { Component, Injector,  Inject, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { AlipaySettingEditDto } from "@shared/model/alipaySettingdto";
import { AppComponentBase } from "@shared/component-base/app-component-base";
import { HttpClient } from '@angular/common/http';

@Component({
  templateUrl: './alipaysetting.component.html'
})

export class AlipaySettingComponent extends AppComponentBase implements OnInit {
  active: boolean = false;
  validateForm: FormGroup;
  alipaySetting: AlipaySettingEditDto = null;


  constructor(
    private injector: Injector,
    private httpClient: HttpClient,
    private fb: FormBuilder,
    public msg: NzMessageService,
  ) {
    super(injector);
  }



  showModal(): void {
    this.alipaySetting = new AlipaySettingEditDto();
    this.httpClient.get("alipaysetting/info").subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.alipaySetting.init(result.data);
        }
      });

    this.validateForm.reset();
    this.active = true;
  }



  handleSave(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    if (!this.validateForm.valid) {
      return;
    }

    this.httpClient.post("alipaySetting/edit", this.alipaySetting.toJSON()).subscribe(
      (val) => {
        const result: any = val;
        if (result && !result.success) {
          this.msg.error(result.message);
          return null;
        } else {
          this.msg.create("success", "保存成功！");
        }
      });
  }



  updateConfirmValidator(): void {
    /** wait for refresh value */
    Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
  };

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      id: [null],
      appId: [null, [Validators.required]],
      gatewayUrl: [null, [Validators.required]],
      merchantPrivateKey: [null, [Validators.required]],
      alipayPublicKey: [null, [Validators.required]],
      notifyUrl: [null],
      returnUrl: [null],
    });

    this.active = true;
    this.validateForm.reset();
    this.showModal();
  }
}
